<?php

class AccessFilter extends CFilter
{

	/**
	 * @param CFilterChain $filterChain the filter chain that the filter is on.
	 * @return boolean
	 * @throw CHttpException
	 */
	public function preFilter($filterChain)
	{
		$user = Yii::app()->user; /* @var $user WebUser */
		if ($user->getIsGuest()) {
			$user->loginRequired();
		}
		if ($user->getIsAdmin()) {
			return true;
		}
		$project = $filterChain->controller->projectName;
		$route = $filterChain->controller->route;
		if (!strncmp($route, 'user/', 5) && $route !== 'user/profile') {
			$this->accessDenied();
		}
		if (!array_key_exists($route, Yii::app()->params['accessList'])) {
			return true;
		}
		// check access
		if ($route === 'data/list' || $route === 'project/schmea') {
			$route = null;
		}
		if (!$user->getModel()->hasAccess($project, $route)) {
			$this->accessDenied();
		}
		return true;
	}

	protected function accessDenied($message = 'Permission denied')
	{
		throw new CHttpException(403, $message);
	}
}
